const Router = require("koa-router");
//访问前缀
const router = new Router({ prefix: "/nginx" });
const fs = require("fs");

router.get("/nginx/get", async (ctx) => {
  if (!ctx.session.isLogin) {
    ctx.body = {
      code: -2,
      msg: "未登录",
    };
    return;
  }
  let { curPath } = ctx.query;
  console.log(">>", curPath);

  try {
    const content = fs.readFileSync(curPath).toString();
    ctx.body = {
      code: 0,
      data: content,
      msg: "成功",
    };
  } catch (e) {
    ctx.body = {
      code: -3,
      msg: e.message,
    };
  }
});

router.get("/nginx/multipleGet", async (ctx) => {
  if (!ctx.session.isLogin) {
    ctx.body = {
      code: -2,
      msg: "未登录",
    };
    return;
  }
  let { curPath } = ctx.query;
  console.log(">>", curPath);

  let files = [];
  try {
    files = fs.readdirSync(curPath);
  } catch (e) {
    ctx.body = {
      code: -3,
      msg: e.message,
    };
    return;
  }

  let result = [];
  // files [ 'args.json', 'temp.sh', 'test.sh' ]
  let filesFilter = files.filter((item) => {
    // if ([].includes(item)) {
    //   return false;
    // }
    if (item.startsWith(".")) {
      return false;
    }
    return true;
  });
  console.log(filesFilter);

  filesFilter.forEach((filePath) => {
    console.log(`'${filePath}'`);
    let info = { name: filePath, content: "", desc: "" };
    try {
      const content = fs.readFileSync(`${curPath}/${filePath}`).toString();
      info.content = content;
      result.push(info);
    } catch (e) {
      console.log("非文件", e.message);
    }
  });
  ctx.body = {
    code: 0,
    data: result,
    msg: "成功",
  };
});

router.get("/https/get", async (ctx) => {
  if (!ctx.session.isLogin) {
    ctx.body = {
      code: -2,
      msg: "未登录",
    };
    return;
  }
  let { curPath } = ctx.query;
  console.log(">>", curPath);

  let files = [];
  let finalPath = curPath + (curPath.endsWith("/") ? "" : "/") + "cert";
  let isExist = true;
  try {
    fs.statSync(finalPath);
  } catch (e) {
    // stats 失败 Error: ENOENT: no such file or directory, stat '/etc/nginx/cert'
    // 文件不存在，创建该目录
    isExist = false;
  }

  try {
    !isExist && fs.mkdirSync(finalPath);
    files = fs.readdirSync(finalPath);
  } catch (e) {
    ctx.body = {
      code: -3,
      msg: e.message,
    };
    return;
  }

  let result = [];
  // files [ 'args.json', 'temp.sh', 'test.sh' ]
  let filesFilter = files.filter((item) => {
    // if ([].includes(item)) {
    //   return false;
    // }
    if (item.startsWith(".")) {
      return false;
    }
    return true;
  });
  console.log(filesFilter);

  filesFilter.forEach((filePath) => {
    console.log(`'${filePath}'`);
    let info = { name: filePath, content: "", desc: "" };
    const content = fs.statSync(`${finalPath}/${filePath}`);
    info.content = content;
    result.push(info);
  });
  ctx.body = {
    code: 0,
    data: result,
    msg: "成功",
  };
});

module.exports = router;
